package com.soft.util.encrypt;

import javax.crypto.Cipher;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

public class RSA {
	public static final String  SIGN_ALGORITHMS = "SHA1WithRSA";

	public static String privateKeySign(String content, String privateKey) {
		try {
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
			KeyFactory keyf = KeyFactory.getInstance("RSA");
			PrivateKey priKey = keyf.generatePrivate(priPKCS8);

			java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

			signature.initSign(priKey);
			signature.update(content.getBytes("utf-8"));

			byte[] signed = signature.sign();
			// System.out.printf("%02x ",signed[i]);

			return Base64.encode(signed);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	
	 public static PrivateKey getPrivateKey(String key) {
	        byte[] keyBytes;
	        keyBytes = Base64.decode(key);
	        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
	        KeyFactory keyFactory;
	        try {
	            keyFactory = KeyFactory.getInstance("RSA");
	            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
	            return privateKey;
	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	        
	        return null;
	    }
	 public static String decrypt(PrivateKey prikey,String content) throws Exception {
	        Cipher cipher = Cipher.getInstance("RSA");
	        cipher.init(Cipher.DECRYPT_MODE, prikey);
	        InputStream ins = new ByteArrayInputStream(Base64.decode(content));
	        ByteArrayOutputStream writer = new ByteArrayOutputStream();
	        //rsa解密的字节大小最多是128，将需要解密的内容，按128位拆开解密
	        byte[] buf = new byte[128];
	        int bufl;
	        while ((bufl = ins.read(buf)) != -1) {
	            byte[] block = null;
	            if (buf.length == bufl) {
	                block = buf;
	            } else {
	                block = new byte[bufl];
	                for (int i = 0; i < bufl; i++) {
	                    block[i] = buf[i];
	                }
	            }
	            writer.write(cipher.doFinal(block));
	        }
	        return new String(writer.toByteArray(), "utf-8");
	    }

}
